package com.b.sts.util;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 创建公用线程池 工具类
 * 懒汉
 *
 * @author boy
 */
public class ThreadUtil {
    private static volatile ThreadPoolExecutor threadPool = null;


    private ThreadUtil() {
    }

    /**
     * 双重加锁
     */
    public static ThreadPoolExecutor getThreadPool() {
        if (threadPool == null || threadPool.isShutdown()) {
            synchronized (ThreadUtil.class) {
                if (threadPool == null || threadPool.isShutdown()) {
                    int processors = Runtime.getRuntime().availableProcessors();
                    threadPool = new ThreadPoolExecutor(
                            processors,
                            processors * 2,
                            30,
                            TimeUnit.SECONDS,
                            new LinkedBlockingDeque<>(128),
                            Executors.defaultThreadFactory(),
                            new ThreadPoolExecutor.DiscardOldestPolicy()
                    );
                }
            }
        }
        return threadPool;
    }

    /**
     * 执行任务
     *
     * @param command 逻辑代码
     */
    public static void execute(Runnable command) {
        getThreadPool().execute(command);
    }

    /**
     * 执行任务，为True才执行
     *
     * @param b       触发布尔
     * @param command 逻辑代码
     */
    public static void executeTrue(boolean b, Runnable command) {
        if (b) {
            execute(command);
        }
    }

    /**
     * 执行任务，为False才执行
     *
     * @param b       触发布尔
     * @param command 逻辑代码
     */
    public static void executeFalse(boolean b, Runnable command) {
        if (!b) {
            execute(command);
        }
    }
}
